package com.snap.awesomeserial.dialog;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.InputFilter;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.TextView;

import com.snap.awesomeserial.R;
import com.snap.awesomeserial.utils.ToastUtils;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.jessyan.autosize.utils.AutoSizeUtils;

public class NumberInputDialog extends DialogFragment {

    private int dotCount;
    private String currentValue;
    private float maxValue;
    private float minValue;
    private String unitName;
    private int maxLength = 3;
    private int xDp;

    private TextView valueEt;
    private OnValueListener listener;
    private TextView num0;
    private TextView num1;
    private TextView num2;
    private TextView num3;
    private TextView num4;
    private TextView num5;
    private TextView num6;
    private TextView num7;
    private TextView num8;
    private TextView num9;

    private TextView dot;


    private ImageView back;


    public NumberInputDialog setParam(TextView TextView, String unitName, int xDp, int length, OnValueListener listener) {
        this.dotCount = 2;
        this.maxValue = 100;
        this.minValue = 100;
        this.maxLength = length;
        this.valueEt = TextView;
        this.xDp = xDp;
        String value = valueEt.getText().toString().trim();
        Pattern compile = Pattern.compile("\\d+\\.*\\d*");
        Matcher matcher = compile.matcher(value);
        if (matcher.find()) {
            this.currentValue = matcher.group();
        } else {
            currentValue = "";
        }
        this.unitName = unitName;
        this.listener = listener;

        return this;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_TITLE, R.style.DimDialogStyle);

    }

    @Override
    public void onStart() {
        super.onStart();
        getDialog().setCanceledOnTouchOutside(true);
        Window win = getDialog().getWindow();
        win.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams params = win.getAttributes();
        params.gravity = Gravity.BOTTOM | Gravity.START;
        params.x = AutoSizeUtils.dp2px(getContext(), xDp);
        params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        win.setAttributes(params);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.dialog_number, container, false);

        num0 = v.findViewById(R.id.num0);
        num1 = v.findViewById(R.id.num1);
        num2 = v.findViewById(R.id.num2);
        num3 = v.findViewById(R.id.num3);
        num4 = v.findViewById(R.id.num4);
        num5 = v.findViewById(R.id.num5);
        num6 = v.findViewById(R.id.num6);
        num7 = v.findViewById(R.id.num7);
        num8 = v.findViewById(R.id.num8);
        num9 = v.findViewById(R.id.num9);

        dot = v.findViewById(R.id.num_dot);


        back = v.findViewById(R.id.num_back);


        valueEt.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
//        valueEt.setText(new BigDecimal(String.valueOf(value)).stripTrailingZeros().toPlainString());

        View.OnClickListener numListener = v12 -> {
            if (currentValue.contains(".")) {
                String[] sp = currentValue.split("\\.");
                if (sp.length > 1 && sp[1].length() >= dotCount) {
                    return;
                }
            }
            if (currentValue.length() >= maxLength && Float.valueOf(currentValue) != -1) {
                return;
            }
            if (currentValue.equals("0")) {
                currentValue = "";
            }
            if (currentValue.equals("-1")) {
                currentValue = "";
            }
            switch (v12.getId()) {
                case R.id.num0:
                    currentValue += "0";
                    break;
                case R.id.num1:
                    currentValue += "1";
                    break;
                case R.id.num2:
                    currentValue += "2";
                    break;
                case R.id.num3:
                    currentValue += "3";
                    break;
                case R.id.num4:
                    currentValue += "4";
                    break;
                case R.id.num5:
                    currentValue += "5";
                    break;
                case R.id.num6:
                    currentValue += "6";
                    break;
                case R.id.num7:
                    currentValue += "7";
                    break;
                case R.id.num8:
                    currentValue += "8";
                    break;
                case R.id.num9:
                    currentValue += "9";
                    break;
                default:
            }
            updateEt();
        };

        num0.setOnClickListener(numListener);
        num1.setOnClickListener(numListener);
        num2.setOnClickListener(numListener);
        num3.setOnClickListener(numListener);
        num4.setOnClickListener(numListener);
        num5.setOnClickListener(numListener);
        num6.setOnClickListener(numListener);
        num7.setOnClickListener(numListener);
        num8.setOnClickListener(numListener);
        num9.setOnClickListener(numListener);

        dot.setOnClickListener(v13 -> {
            if (currentValue.length() >= maxLength && Float.valueOf(currentValue) != -1) {
                return;
            }
            if (currentValue.equals("-1")) {
                currentValue = "";
            }
            if (dotCount == 0) {
                return;
            }
            if (currentValue.contains(".")) {
                return;
            }
            currentValue += ".";
            updateEt();
        });

        back.setOnClickListener(v13 -> {
            if (currentValue.length() == 0 || Float.valueOf(currentValue) == -1) {
                currentValue = "-1";
            } else {
                currentValue = currentValue.substring(0, currentValue.length() - 1);
            }
            if (currentValue.length() == 0) {
                currentValue = "-1";
            }
            updateEt();
        });
        return v;
    }

    private void updateEt() {
        if (Float.valueOf(currentValue) == -1) {
            valueEt.setText("-");
        } else {
            valueEt.setText(currentValue + unitName);
        }
        listener.onValueChanged(Float.valueOf(currentValue));
    }

    public void check() {
        float resValue = Float.parseFloat(valueEt.getText().toString());
        if (resValue > maxValue || resValue < minValue) {
            ToastUtils.get().showText(String.format("输入超出范围[ %s , %s ]，请修改！",
                    new BigDecimal(String.valueOf(minValue)).stripTrailingZeros().toPlainString(),
                    new BigDecimal(String.valueOf(maxValue)).stripTrailingZeros().toPlainString()));
            return;
        }
        NumberInputDialog.this.dismiss();
    }


    public interface OnValueListener {
        void onValueChanged(float value);
    }
}